package org.grow.wsing.chat;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: xwg
 * @CreateDate: 2025/10/16
 */

// ServerEndpoint 既是http请求 又是websocket通信
@Component
@ServerEndpoint("/chat/{uid}")
public class WsServer {


    //    该类不属于spring 构造 属于多例 所以公用变量需要考虑static保证唯一
    public static ConcurrentHashMap<String, SessionEx> chatroom = new ConcurrentHashMap<>();
    //    群组
    public static ConcurrentHashMap<String, SessionEx> roomA = new ConcurrentHashMap<>();
    public static ConcurrentHashMap<String, SessionEx> roomZ = new ConcurrentHashMap<>();


    //    public static ConcurrentHashMap<String, ConcurrentHashMap<String, SessionEx> > AllRooms = new ConcurrentHashMap<>();
    @OnOpen
    public void connected(Session session, @PathParam("uid") String uid) {
        System.out.println(uid + "连接上了");
        System.out.println("sid" + session.getId());
        SessionEx sessionEx = new SessionEx();
        sessionEx.setUid(uid);
        sessionEx.setSession(session);
        chatroom.put(session.getId(), sessionEx);
        System.out.println("当前聊天室 共有的人数是：" + chatroom);
        if (uid.startsWith("z")) {
            roomZ.put(session.getId(), sessionEx);
            System.out.println("当前聊天室z 共有的人数是：" + roomZ);

        }

    }

    private ObjectMapper objectMapper = new ObjectMapper();

    //  全体群发  群内群发  双人单聊  踢人下线
    @OnMessage
    public void receiveMessage(Session session, String message, @PathParam("uid") String uid) {
/**
 * 消息解析
 * */
        System.out.println("收到来自信息" + message + "-- " + uid + session.getId());
        MyMessage myMessage;
        try {
            myMessage = objectMapper.readValue(message, MyMessage.class);

        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        System.out.println("收到并解析出信息:" + myMessage);
//        服务端发起
//        session.getAsyncRemote().sendText("from server： "+message+" --" +uid);
//        for (String key : chatroom.keySet()) {
//            SessionEx sessionEx = chatroom.get(key);
//            sessionEx.getSession().getAsyncRemote().sendText("from server: " + uid + " 说 " + message);
//        }
        if (myMessage == null) {
            return;
        }
        if (myMessage.getUrl() == null) {
            return;
        }
//        RequestMapping
//        @MessageMapping
        if (myMessage.getUrl().equals("all")) {
//            群发
            for (String key : chatroom.keySet()) {
                SessionEx sessionEx = chatroom.get(key);
                sessionEx.getSession().getAsyncRemote().sendText("from server: " + uid + " 说 " + message);
            }
        } else if (myMessage.getUrl().contains("roomZ")) {
            if (uid.startsWith("z")) {
                for (String key : roomZ.keySet()) {
                    SessionEx sessionEx = roomZ.get(key);
                    sessionEx.getSession().getAsyncRemote().sendText("from server: " + uid + " 说 " + message);
                }
            }
        } else if (myMessage.getUrl().contains("single")) {
            System.out.println("单聊 " + uid + "  " + myMessage.getTo());
//            单聊给对面发
            String to = myMessage.getTo();
            for (String key : chatroom.keySet()) {
                SessionEx sessionEx = chatroom.get(key);
                if (sessionEx.getUid().equals(to)) {
                    sessionEx.getSession().getAsyncRemote().sendText("from server: " + uid + " 说 " + message);
                }

            }
//            单聊给自己发
            session.getAsyncRemote().sendText("from server: " + uid + " 说 " + message);
        } else if (myMessage.getUrl().contains("serious")) {
            String content = myMessage.getContent();
            System.out.println("seriousing ");
            if (content.contains("feifa")) {
                try {
                    session.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            } else {
                for (String key : chatroom.keySet()) {
                    SessionEx sessionEx = chatroom.get(key);
                    sessionEx.getSession().getAsyncRemote().sendText("from server: " + uid + " 说 " + message);
                }
            }

        }

    }

    @OnClose
    public void closed(Session session, @PathParam("uid") String uid) {

        System.out.println(uid + "断开连接");
        if (session != null) {

            chatroom.remove(session.getId());
        }
        if (uid.startsWith("z")) {
            roomZ.remove(session.getId());
        }
        System.out.println("当前总聊天室 共有的人数是：" + chatroom);
        System.out.println("当前聊天室z 共有的人数是：" + roomZ);
    }
}
